<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>胶温度监控</title>
    <script src="js/highcharts.js"></script>
	<script src="js/site.configuration.js"></script>
    <script src="/lib/js/durr.emos.js"></script>
    <style>
        body {
            background: #ffffff;
            margin: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            font-family: 'Inter', sans-serif;
        }
        #container {
            width: 700px;
            height: 100vh;
            background: #ffffff;
			margin-left: -5vh;
        }
    </style>
</head>
<body>
    <div id="container"></div>

    <script>
        // 初始化配置
        Highcharts.setOptions({
            lang: { numericSymbols: null }
        });

        // 创建图表
        const chart = Highcharts.chart('container', {
            chart: {
                type: 'areaspline',
                backgroundColor: 'transparent',
                margin: [40, 25, 60, 60],
                animation: { duration: 300 }
            },
            title: {
                text: '胶温度监控',
                style: {
                    color: '#003254',
                    fontSize: '20px',
                    fontWeight: 500
                }
            },
            xAxis: {
                type: 'datetime',
                tickInterval: 500,
                labels: {
                    style: { color: '#89bad3' },
                    formatter: function() {
                        return Highcharts.dateFormat('%H:%M:%S', this.value);
                    }
                },
                gridLineColor: '#e0e0e0',
                lineColor: '#89bad3'
            },
            yAxis: {
                title: { text: null },
                labels: { style: { color: '#89bad3' } },
                gridLineColor: '#e0e0e0',
                min: 0,
                max: 100,
                plotLines: []
            },
            series: [{
                name: '温度值',
                color: {
                    linearGradient: { x1: 0, x2: 0, y1: 0, y2: 1 },
                    stops: [
                        [0, 'rgba(67,142,255,0.8)'],
                        [1, 'rgba(67,142,255,0.1)']
                    ]
                },
                lineWidth: 2,
                marker: { enabled: false },
                fillOpacity: 0.3,
                data: []
            }],
            plotOptions: {
                line: {
                    dataLabels: {
                        enabled: true
                    },
                    enableMouseTracking: true
                }
            },
            tooltip: {
                shared: true,
                backgroundColor: 'rgba(255,255,255,0.95)',
                borderColor: '#ddd',
                style: { color: '#333' },
                formatter: function() {
                    return `<b>${Highcharts.dateFormat('%H:%M:%S', this.x)}</b><br/>
                            ${this.points.map(p => 
                                `${p.series.name}: ${p.y.toFixed(1)}℃`
                            ).join('<br/>')}`;
                }
            },
            credits: { enabled: false },
            legend: { enabled: false }
        });

        // 数据管理
        let dataPoints = [];
        let currentTime = Date.now();
        let maxLabel, minLabel, avgLineId = null;

        // 更新统计标注
        const updateStats = (data) => {
            const values = data.map(d => d[1]);
            const max = Math.max(...values);
            const min = Math.min(...values);
            const avg = values.reduce((a,b) => a + b, 0) / values.length;

            // 移除旧标注
            if(maxLabel) maxLabel.destroy();
            if(minLabel) minLabel.destroy();
            if(avgLineId) {
                chart.yAxis[0].removePlotLine(avgLineId);
                avgLineId = null;
            }

            // 添加最大值标注
            maxLabel = chart.renderer.label(
                `最大: ${max.toFixed(1)}℃`,
                chart.plotWidth - 120,
                20
            ).css({
                color: '#ff4444',
                fontSize: '12px',
                fontWeight: 'bold'
            }).add();

            // 添加最小值标注
            minLabel = chart.renderer.label(
                `最小: ${min.toFixed(1)}℃`,
                chart.plotWidth - 120,
                40
            ).css({
                color: '#44aaff',
                fontSize: '12px',
                fontWeight: 'bold'
            }).add();

            // 添加唯一平均值标线
            avgLineId = chart.yAxis[0].addPlotLine({
                value: avg,
                color: '#00cc88',
                width: 2,
                dashStyle: 'Dash',
                id: 'avg-line', // 固定ID
                label: {
                    text: `平均: ${avg.toFixed(1)}℃`,
                    align: 'right',
                    style: { color: '#00cc88' }
                }
            }).id;
        };

        // 数据更新
        setInterval(() => {
            currentTime += 500;
            //const newValue = Math.random() * 100;
            const newValue = emosWS.getTagValue("tag_1"); //读取PLC数据并且刷新
            console.log("Update")
            // 维护数据队列
            dataPoints.push([currentTime, newValue]);
            if (dataPoints.length > 20) dataPoints.shift();

            // 更新图表
            chart.series[0].setData(dataPoints);
            if(dataPoints.length > 1) updateStats(dataPoints);
            
            // 调整时间轴范围
            chart.xAxis[0].setExtremes(
                currentTime - 9500,
                currentTime + 500
            );
        }, 500);
    </script>
</body>
</html>